from sqlalchemy import Column, String, Boolean, Float, Integer, JSON

from common.exchanges.entities import ApiAuthInfo
from common.models import ModelBase


class AccountGroup(ModelBase):
    __tablename__ = 'gtp_account_group'
    id = Column(String(128), primary_key=True, )
    user_id = Column(String(128), nullable=False, index=True)
    name = Column(String(64), nullable=False)
    is_active = Column(Boolean, default=True, comment='是否活跃')


class Account(ModelBase):
    __tablename__ = 'gtp_account'
    id = Column(String(128), primary_key=True, )
    user_id = Column(String(128), nullable=False, index=True)
    group_id = Column(String(128), )
    exchange = Column(String(32), nullable=False)
    name = Column(String(64), nullable=True)
    api_key = Column(String(128), nullable=False)
    api_secret = Column(String(128), nullable=False)

    def to_auth_info(self):
        return ApiAuthInfo(
            api_secret=self.api_secret, api_key=self.api_key,
        )


class PerpetualInterestRecord(ModelBase):
    __tablename__ = 'gtp_perpetual_interest_record'
    exchange = Column(String(32), nullable=False, index=True)
    instrument = Column(String(64), nullable=False)
    interest = Column(Float, comment='资金费率')
    timestamp = Column(Integer, index=True)


class TradeOrder(ModelBase):
    __tablename__ = 'gtp_trade_order'

    id = Column(String(128), primary_key=True, )
    type = Column(String(32), comment='订单类型')
    status = Column(String(32), default='running', )


class TradeTask(ModelBase):
    __tablename__ = 'gtp_trade_task'

    class TaskType:
        DeltaHedge = 'delta_hedge'
        FutureSwap = 'future_swap'

    class TaskStatus:
        Running = 'running'
        Completed = 'completed'
        Failed = 'failed'

    id = Column(String(128), primary_key=True, )
    user_id = Column(String(128), nullable=False)
    account_id = Column(String(128), nullable=False)
    exchange = Column(String(32),)
    currency = Column(String(16), )
    type = Column(String(32), comment='任务类型', nullable=False)
    status = Column(String(32), default=TaskStatus.Running, )
    params = Column(JSON, nullable=True)
    data = Column(JSON, nullable=True)
    error_msg = Column(String(512), nullable=True, default=None)
